import { defineStore } from 'pinia'
import { loginApi } from '@/api/auth/login.ts'
import type { User } from '@/types/User'
import type { ApiResponse } from '@/api/types'

// 与数据库 users 表结构对齐的初始用户对象
const emptyUser: User = {
  id: 0,
  username: '',
  email: '',
  password_hash: undefined,
  display_name: null,
  avatar_url: null,
  settings: null,
  is_active: true,
  created_at: '',
  updated_at: ''
}

export const useUserStore = defineStore('user', {
  state: () => ({
    user: { ...emptyUser } as User,
    loading: false,
    userId: null as number | null
  }),
  persist: {
    key: 'mirrorforest-user-store',
    storage: window.localStorage,
    paths: ['user','userId']
  } as any,
  actions: {
    setUser(data: any) {
      let payload: any = data
      if (payload && typeof payload === 'object') {
        if ('user' in payload && (payload as any).user) {
          payload = (payload as any).user
        } else if ('data' in payload && (payload as any).data) {
          const d: any = (payload as any).data
          payload = d && typeof d === 'object' && 'user' in d && d.user ? d.user : d
        }
      } else {
        payload = {}
      }
      this.user = {
        ...emptyUser,
        ...this.user,
        ...(payload || {}),
      }
      // 如果后端返回了有效 id，更新并持久化
      if (typeof this.user.id === 'number' && this.user.id > 0) {
        this.userId = this.user.id
      }
    },
    clearUser() {
      this.user = { ...emptyUser }
      this.userId = null
      this.loading = false
    },
    async login(payload: { email: string; password: string; captchaId?: string; captchaCode?: string }) {
      const res: ApiResponse<{userId: number}> = await loginApi(payload)
      console.log('登录响应:', res)
      this.user.id = res.data?.userId || 0;
        if ((res.code === 0 || res.code === 200) && res.success !== false) {
          // 兼容后端 data 为空的情况：先写入后端数据，然后用表单回填最小字段
          this.setUser(res?.data ?? {})
          if (!this.user.email && payload?.email) {
            this.setUser({ email: payload.email })
          }
          if (!this.user.username && payload?.email) {
            const name = (payload.email.split('@')[0] || '').trim()
            if (name) this.setUser({ username: name })
          }
          // 回填后若仍无 id，可保持 null，等待后端后续接口返回再 setUser
          return true
        }
      throw new Error(res.message || '登录失败')
    },

    logout() {
      this.clearUser()
      this.userId = null
    }
  },
  getters: {
    isActive: (state) => state.user.is_active === true,
    getUserId: (state) => state.userId
  }
})